import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { useAuth } from '@/composables/useAuth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const { isLoggedIn, hasAnyPermission, initAuth } = useAuth()
  
  // 初始化认证状态
  initAuth()

  // 开发模式：跳过所有权限检查
  if (import.meta.env.DEV) {
    // 如果访问登录页，直接跳转到管理页面
    if (to.path === '/login') {
      next('/dashboard')
      return
    }
    next()
    return
  }

  // 生产模式的权限检查
  if (to.meta.requiresAuth) {
    if (!isLoggedIn.value) {
      next('/login')
      return
    }

    if (to.meta.permissions && to.meta.permissions.length > 0) {
      if (!hasAnyPermission(to.meta.permissions)) {
        next('/dashboard')
        return
      }
    }
  }

  if (to.path === '/login' && isLoggedIn.value) {
    next('/dashboard')
    return
  }

  next()
})

export default router